package com.hcb.tonguetiphealth.widget;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.Comment;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;

public class CommentAddWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "CommentAddWidget";
	private String url = Global.URL + Global.servlet_comment;
	
	private final int intProduct = 0;
	private final int intEnvironment = 1;
	private final int intServe = 2;
	
	private Activity ctx;
	private Handler mHandler;
	private Button product, environment, serve, commit;
	private LinearLayout back;
	private TextView tv_whole, tv_product, tv_environment, tv_environment_id, tv_serve;
	private EditText remark;
	private RatingBar ratingBar;
	private String strWhole, strProduct, strEnvironment, strServe, strRemark;
	private List<Comment> commentList;
	private Comment comment;
	private boolean commentSucceed = false;
	
	private ListView listView;
	private SelectionListAdapter adapter;
	private List<String> strList;
	private PopupWindow popupWindow;
	
	private String typeId;
	private String targetId;
	
	public CommentAddWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.comment_add, this); 
		
		typeId = ctx.getIntent().getStringExtra("typeId");
		targetId = ctx.getIntent().getStringExtra("targetId");
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在提交评论...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if(commentSucceed) {
						showMessage(ctx, "评论成功");
						ctx.getIntent().putExtra("commentSucceed", commentSucceed);
						ctx.setContentView(new CommentWidget(ctx));
					} else {
						showMessage(ctx, "评论失败");
					}
					dismissMessageDialog();
					break;
				}
			}
		};
		ratingBar = (RatingBar)findViewById(R.id.comment_add_rating_ratingbar);
		tv_whole = (TextView)findViewById(R.id.drinks_book_comment_whole_textview);
		tv_product = (TextView)findViewById(R.id.drinks_book_comment_add_product_textview);
		tv_environment_id = (TextView)findViewById(R.id.drinks_book_comment_add_environment_textview_id);
		tv_environment = (TextView)findViewById(R.id.drinks_book_comment_add_environment_textview);
		tv_serve = (TextView)findViewById(R.id.drinks_book_comment_add_serve_textview);
		remark = (EditText)findViewById(R.id.drinks_book_comment_remark_edittext);
		back = (LinearLayout)findViewById(R.id.comment_add_back_button);
		product = (Button)findViewById(R.id.drinks_book_comment_add_product_button);
		environment = (Button)findViewById(R.id.drinks_book_comment_add_environment_button);
		serve = (Button)findViewById(R.id.drinks_book_comment_add_serve_button);
		commit = (Button)findViewById(R.id.comment_add_commit_button);
		back.setOnClickListener(this);
		product.setOnClickListener(this);
		environment.setOnClickListener(this);
		serve.setOnClickListener(this);
		commit.setOnClickListener(this);
		ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			@Override
			public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
				// TODO Auto-generated method stub
				if(1 == rating) {
					tv_whole.setText("不满意");
					strWhole = "1";
				} else if(2 == rating) {
					tv_whole.setText("一般");
					strWhole = "2";
				} else if(3 == rating) {
					tv_whole.setText("满意");
					strWhole = "3";
				} else {
					tv_whole.setText("");
				}
			}
		});
		initData();
		commentList = new ArrayList<Comment>();
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.comment_add_back_button:
			ctx.getIntent().putExtra("commentSucceed", commentSucceed);
			ctx.setContentView(new CommentWidget(ctx));
			break;
		case R.id.drinks_book_comment_add_product_button:
			popupWindow = makePopupWindow(ctx, intProduct);
			popupWindow.showAsDropDown(product);
			break;
		case R.id.drinks_book_comment_add_environment_button:
			popupWindow = makePopupWindow(ctx, intEnvironment);
			popupWindow.showAsDropDown(environment);
			break;
		case R.id.drinks_book_comment_add_serve_button:
			popupWindow = makePopupWindow(ctx, intServe);
			popupWindow.showAsDropDown(serve);
			break;
		case R.id.comment_add_commit_button:
			commit();
			break;
		default:
			break;
		}
	}
	private void initData() {
		/*
		 *  typeId = 17   // 酒水
			typeId = 4   // 商家评论
			typeId = 16   // 套餐
			typeId = 16   // 菜品
		 */
		if(typeId != null && typeId.equals("17")) {
			tv_environment_id.setText(R.string.drinks_book_comment_environment3);
			remark.setHint(R.string.drinks_book_comment_remark_hint3);
		}
		strList = new ArrayList<String>();
		strList.add("差");
		strList.add("一般");
		strList.add("好");
		strList.add("很好");
		strList.add("非常好");
	}
	private void commit() {
		if(StringUtils.isEmpty(tv_whole.getText().toString())) {
			showMessage(ctx, "请选择整体评价");
			return;
		}
		if(StringUtils.isEmpty(tv_product.getText().toString())) {
			showMessage(ctx, "请选择对产品的评价");
			return;
		}
		if(StringUtils.isEmpty(tv_environment.getText().toString())) {
			showMessage(ctx, "请选择对环境的评价");
			return;
		}
		if(StringUtils.isEmpty(tv_serve.getText().toString())) {
			showMessage(ctx, "请选择对服务的评价");
			return;
		}
		strRemark = remark.getText().toString();
		if(StringUtils.isEmpty(strRemark)) {
			showMessage(ctx, "请填写你对该商家的看法");
			return;
		}
		
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);

		new Thread() {
			public void run() {
				commentSucceed = false;
				String response = null;
				try {
					typeId = typeId==null ? "" : typeId;
					targetId = targetId==null ? "" : targetId;
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("typeId", typeId));
					params.add(new BasicNameValuePair("targetId", targetId));//373
					params.add(new BasicNameValuePair("user", Global.user.getUserName()));
					params.add(new BasicNameValuePair("time", System.currentTimeMillis()+""));
					params.add(new BasicNameValuePair("content", strRemark));
					params.add(new BasicNameValuePair("rating", strWhole));
					params.add(new BasicNameValuePair("product", strProduct));
					params.add(new BasicNameValuePair("environment", strEnvironment));
					params.add(new BasicNameValuePair("serve", strServe));
					response = HttpUtils.Post(url, params);
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
					
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							
						} else {
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									comment = new Comment();
									
									comment.setUser(getString(jObject, "username"));
									comment.setTime(getString(jObject, "addtime"));
									comment.setContent(getString(jObject, "content"));
									comment.setProduct(getString(jObject, "produce"));
									comment.setEnvironment(getString(jObject, "environment"));
									comment.setServe(getString(jObject, "serve"));
									comment.setRating(StringUtils.parseFloat(getString(jObject, "star")));
									
									commentList.add(comment);
								}
							}
							if(commentList.size() > 0) {
								commentSucceed = true;
								Global.commentList = commentList;
							}
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	//创建一个包含自定义view的PopupWindow
	private PopupWindow makePopupWindow(Context cx, final int flag) {
	    PopupWindow window;
	    window = new PopupWindow(cx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.drinks_book_dialog_list, null); 
        listView = (ListView)view.findViewById(R.id.drinks_book_dialog_listview);
        adapter = new SelectionListAdapter(ctx, strList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				String result = (String)arg0.getAdapter().getItem(arg2);
				switch(flag) {
				case intProduct:
					tv_product.setText(result);
					strProduct = arg2 +"";
					break;
				case intEnvironment:
					tv_environment.setText(result);
					strEnvironment = arg2 +"";
					break;
				case intServe:
					tv_serve.setText(result);
					strServe = arg2 +"";
					break;
				}
				popupWindow.dismiss();
			}
		});
	    
	    final Resources res = cx.getResources();
	    view.setBackgroundColor(res.getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    window.setWidth(product.getWidth());
	    window.setHeight(LayoutParams.WRAP_CONTENT);
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    //window.setHeight(res.getDimensionPixelSize(R.dimen.page_window_height));
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	
	@Override
	public void notifyAdapter() {
		
	}
}
